package com.founder.barcode.bussiness.code.service;

import java.sql.SQLException;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.founder.barcode.bussiness.constant.Const;
import com.founder.barcode.common.util.UUIDGenerator;
import com.founder.barcode.persistence.bussiness.dao.ICodeCheckLogDAO;
import com.founder.barcode.persistence.bussiness.dao.IQrCodeInfoDAO;
import com.founder.barcode.persistence.bussiness.po.CodeCheckLogPO;
import com.founder.barcode.persistence.bussiness.po.QrCodeInfoPO;

@Service
public class CodeCheckLogService {
    
    @Autowired
    private ICodeCheckLogDAO codeCheckLogDAO;
    
    @Autowired
    private IQrCodeInfoDAO qrCodeInfoDAO;
    
    
    /**
     * 彩码机具请求省平台验码：传递的码内容是MD5加密的值，从数据库根据这个字段去匹配content_md5
     * 
     * @param code
     *            扫码或者手工输入码
     * @param mode
     *            1：辅助码串；2：码内容
     * @return
     * @throws SQLException 
     * @throws Exception
     */
    public QrCodeInfoPO getCodeDetailInfoByCode(String content,
            String contentType) throws SQLException {
        QrCodeInfoPO codeInfoPO = null;
        if (Const.DEVICE_CODE_MODE_2.equals(contentType)) {// 码内容

            // 设备扫码,需要从码表中取得公共信息域和个性化信息域内容
            int length = Integer.valueOf(content.substring(3, 6)); // 公共信息域长度

            // 辅助码串(公共信息域中的后24位)
            String business_detail = content.substring(36, length);
            codeInfoPO = qrCodeInfoDAO
                    .getCodeInfoByBusinessDetail(business_detail);

        } else if (Const.DEVICE_CODE_MODE_1.equals(contentType)) {// 辅助码
            codeInfoPO = qrCodeInfoDAO.getCodeInfoByAssistNum(content);
        }
        return codeInfoPO;
    }

    public void save(String contentType,String content,
            String transactionId, String userId, Integer checkChannel) throws SQLException {
        QrCodeInfoPO qr = this.getCodeDetailInfoByCode(content, contentType);
        CodeCheckLogPO cclpo = new CodeCheckLogPO();
        cclpo.setId(new UUIDGenerator().generate());
        cclpo.setSubmitMode(Integer.parseInt(contentType));
        cclpo.setContent(qr.getContent());
        cclpo.setExtContent("");
        cclpo.setCreateTime(new Date());
        cclpo.setStatusCode("1000");
        cclpo.setStatusText("验码成功");
        cclpo.setMessage("验码成功");
        cclpo.setReturnTime(new Date());
        cclpo.setDeviceNum(userId);
        cclpo.setCodeMakeTid(qr.getTransactionId());
        cclpo.setBusinessId(qr.getBusinessId());
        cclpo.setTransactionId(transactionId);
        cclpo.setCheckChannel(checkChannel);
        cclpo.setReversalStatus(1);
        cclpo.setFirmId("");
        cclpo.setOutletId("");
        cclpo.setProdiverId(qr.getBusinessId());
        cclpo.setAssistNum(qr.getAssistNum());
        codeCheckLogDAO.insert(cclpo);
    }
}
